﻿'******************************************************
'******************************************************
'Application Title: Google Widget Editor
'version: 1.0
'Date: 01-02-2008
'Requirements: win2k or later
'Author: Andrew Pye
'Author Email: StretchMasterP@googlemail.com
'License: Released under GNU GENERAL PUBLIC LICENSE v3
'ToDo:
'Changes:Imports System.Text
'******************************************************
'******************************************************

Imports System.Xml.Serialization
Imports System.Web
Public Class frmMain


#Region "Script Error Handler"
    
    'Private Sub InfoBox_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles InfoBox.DocumentCompleted
    '    '        m_htmlDoc = (IHTMLDocument2)axWebBrowser1.Document;
    '    'Dim m_htmlDoc As AxBrowse.AxBrowser
    '    'HTMLWindowEvents2_Event onErrorEvent;
    '    'onErrorEvent = (HTMLWindowEvents2_Event)m_htmlDoc.parentWindow;
    '    'onErrorEvent.onerror += new
    '    'HTMLWindowEvents2_onerrorEventHandler(myHTMLWindowEvents2_onerror);

    '    'Dim doc As HtmlDocument = InfoBox.Document



    '    If Me.InfoBox.Document IsNot Nothing Then



    '        ' Me.InfoBox.Document.Window.AttachEventHandler("Error", AddressOf Window_Error)
    '        '  AddHandler objWind.Error, AddressOf Window_Error
    '    End If
    'End Sub
    ''Private Sub objWind_onerror(ByVal description As String, ByVal url As String, ByVal line As Integer) Handles objWind.onerror
    ''    Debug.Print(description)
    ''End Sub
    'Private Sub Window_Error(ByVal sender As Object, ByVal e As HtmlElementErrorEventArgs)
    '    Debug.Print(e.Description)
    'End Sub
#End Region
#Region "Fields"
    Private o_Widget As New Widget
    Private o_ClassGlobal As New ClassGlobal
    Private o_CodeStoreCollection As CodeStoreCollection
    Private FileName As String = String.Empty
    Private o_CodeHilight As New ClassCodeColor
#End Region

#Region "Properties"
    Public ReadOnly Property Widget() As Widget
        Get
            Return Me.o_Widget
        End Get
    End Property
#End Region

#Region "Form"
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        o_ClassGlobal.Help.LoadList()
        ' TSHelpList.Items.AddRange(o_ClassGlobal.Help.ToArray)
        ShowHideMenu(False, False, False, False, False)
        Me.ShowInfoScreen("Home")
        Me.GgeTreeView1.PopulateTree()
        CodeTree1.LoadData(My.Application.Info.DirectoryPath & "\Data\Java\Java.xml")
        o_ClassGlobal.loadFTPSettings(My.Application.Info.DirectoryPath & "\Data\Settings\FTP.xml")
        'Goto Start Screen
        Me.ShowPreviewScreen(Application.StartupPath & "\Data\Help\Welcome.htm")
        LoadCodeStoreItems(My.Application.Info.DirectoryPath & "\Data\Java\Java.xml")
        'Set up the edit text
        SetupCodeMenuItem()
        Me.o_CodeHilight.CodeEdit = Me.CodeTextBox1

    End Sub
#End Region

#Region "Tree"
    Private Sub GgeTreeView1_NodeSelected(ByRef Node As ClassContainer) Handles GgeTreeView1.NodeSelected
        TSBDelete.Enabled = Node.CanDelete
        DeleteToolStripMenuItem.Enabled = Node.CanDelete
    End Sub
    Private Sub CodeTree1_NodeDoubleClicked(ByRef Node As CodeStore) Handles CodeTree1.NodeDoubleClicked
        Clipboard.Clear()
        Clipboard.SetText(Node.Code)
    End Sub
    Private Sub CodeTree1_NodeSelected(ByRef Node As CodeStore) Handles CodeTree1.NodeSelected
        Me.lblDescription.Text = Node.Description
    End Sub
    Private Sub GgeTreeView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles GgeTreeView1.MouseDown
        'Show/Hide the contect menu based on the node type
        If e.Button = Windows.Forms.MouseButtons.Right Then
            If GgeTreeView1.SelectedNode IsNot Nothing Then
                ShowHideContextMenu(CType(GgeTreeView1.SelectedNode.Tag, ClassContainer).ClassType)
            End If
        End If
    End Sub
    Private Sub GgeTreeView1_NodeMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles GgeTreeView1.NodeMouseClick
        If e.Node.Tag IsNot Nothing Then
            Dim oClassContainer As ClassContainer = CType(e.Node.Tag, ClassContainer)

            If oClassContainer.ClassType = ClassContainer.enumClassType.Content Then
                Dim o_Content As Content = CType(oClassContainer.ClassObject, Content)
                Me.CodeTextBox1.DataBindings.Clear()
                CodeTextBox1.DataBindings.Add(New Binding("Text", o_Content, "Content", False, DataSourceUpdateMode.OnValidation))
                o_CodeHilight.ColorCode()
                Me.ShowCodePropertyGrid(oClassContainer.ClassObject)
                EditToolStripMenuItem1.Enabled = True
                ShowHideMenu(True, True, False, True, True)
            ElseIf oClassContainer.ClassType = ClassContainer.enumClassType.CodeSnippet Then
                Dim o_CodeSnippet As CodeSnippet = CType(oClassContainer.ClassObject, CodeSnippet)
                Me.CodeTextBox1.DataBindings.Clear()
                CodeTextBox1.DataBindings.Add(New Binding("Text", o_CodeSnippet, "Code", True, DataSourceUpdateMode.OnValidation))
                o_CodeHilight.ColorCode()
                Me.ShowCodePropertyGrid(oClassContainer.ClassObject)
                EditToolStripMenuItem1.Enabled = True
                ShowHideMenu(True, True, False, True, True)
            ElseIf oClassContainer.ClassType = ClassContainer.enumClassType.ModulePrefs Then
                Dim o_ModulePrefs As ModulePrefs = CType(oClassContainer.ClassObject, ModulePrefs)
                Me.ShowPropertyGrid(o_ModulePrefs)
                EditToolStripMenuItem1.Enabled = True
                ShowHideMenu(True, True, False, True, True)
            ElseIf oClassContainer.ClassType = ClassContainer.enumClassType.oAuth Then
                Dim o_oAuth As oAuth = CType(oClassContainer.ClassObject, oAuth)
                Me.ShowPropertyGrid(o_oAuth)
                EditToolStripMenuItem1.Enabled = True
                ShowHideMenu(True, True, False, True, True)
            ElseIf oClassContainer.ClassType = ClassContainer.enumClassType.UserPrefs _
           Or oClassContainer.ClassType = ClassContainer.enumClassType.RequireLibs _
           Or oClassContainer.ClassType = ClassContainer.enumClassType.Contents _
           Or oClassContainer.ClassType = ClassContainer.enumClassType.CodeSnippets Then
                Me.ShowInfoScreen(oClassContainer.HelpPage)
                EditToolStripMenuItem1.Enabled = False
                ShowHideMenu(True, True, False, True, True)
            Else
                Me.ShowPropertyGrid(oClassContainer.ClassObject)
                EditToolStripMenuItem1.Enabled = False
                If oClassContainer.ClassType = ClassContainer.enumClassType.UserPref Then
                    ShowHideMenu(True, True, True, True, True)
                Else
                    ShowHideMenu(True, True, False, True, True)
                End If
            End If
        End If
    End Sub
    Private Sub TreeView1_NodeMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs)
        If e.Node.Tag IsNot Nothing Then
            ' PropertyGrid1.SelectedObject = e.Node.Tag
        End If
    End Sub
#End Region

#Region "DisplayLayout"
    Private Sub ShowHideCutCopyPaster(ByVal Enable As Boolean)
        '==========
        'Menu Items
        '==========
        CutToolStripMenuItem1.Enabled = Enable
        CopyToolStripMenuItem1.Enabled = Enable
        PasteToolStripMenuItem1.Enabled = Enable
        SelectAllToolStripMenuItem1.Enabled = Enable
    End Sub
    Private Sub ShowCodeOnly(Optional ByVal oProperty As Object = Nothing)
        PropertyGrid1.Visible = False
        CodeTextBox1.Visible = True
        InfoBox.Visible = False
        TableInput.Visible = True
        PropertyGrid1.SelectedObject = oProperty
        TableInput.SetRow(CodeTextBox1, 1)
        TableInput.SetRowSpan(CodeTextBox1, 2)
        '==========
        'Menu Items
        '==========
        ShowHideCutCopyPaster(True)

    End Sub
    Private Sub ShowCodePropertyGrid(Optional ByVal oProperty As Object = Nothing)
        PropertyGrid1.Visible = True
        CodeTextBox1.Visible = True
        TableInput.Visible = True
        InfoBox.Visible = False
        PropertyGrid1.SelectedObject = oProperty


        TableInput.SetRow(PropertyGrid1, 0)
        TableInput.SetRowSpan(PropertyGrid1, 1)
        TableInput.SetRow(CodeTextBox1, 1)
        TableInput.SetRowSpan(CodeTextBox1, 1)
        '==========
        'Menu Items
        '==========
        ShowHideCutCopyPaster(True)
    End Sub
    Private Sub ShowPropertyGrid(Optional ByVal oProperty As Object = Nothing)
        PropertyGrid1.Visible = True
        CodeTextBox1.Visible = False
        InfoBox.Visible = False
        TableInput.Visible = True
        PropertyGrid1.SelectedObject = oProperty

        TableInput.SetRow(PropertyGrid1, 0)
        TableInput.SetRowSpan(PropertyGrid1, 2)
        ShowHideCutCopyPaster(False)
    End Sub
    Private Sub ShowInfoScreen(ByVal Page As String)
        PropertyGrid1.Visible = True
        CodeTextBox1.Visible = True
        InfoBox.Visible = True
        TableInput.Visible = False
        'Debug.Print(My.Application.Info.DirectoryPath & "\Data\Help\" & Page & ".htm")
        If Me.o_ClassGlobal.Help.Contains(Page.ToUpper) = True Then
            Dim THelp As HelpList = Me.o_ClassGlobal.Help.Item(Page.ToUpper)
            If THelp IsNot Nothing Then
                If THelp.IsLocal = True Then
                    Me.InfoBox.Navigate(My.Application.Info.DirectoryPath & "\Data\" & THelp.Url)
                Else
                    Me.InfoBox.Navigate(THelp.Url)
                End If
            End If
        End If
        ShowHideCutCopyPaster(False)
    End Sub
    Private Sub ShowPreviewScreen(ByVal Page As String, Optional ByVal AutoRefresh As Boolean = False)
        PropertyGrid1.Visible = True
        CodeTextBox1.Visible = True

        InfoBox.Visible = True
        TableInput.Visible = False
        'Debug.Print(My.Application.Info.DirectoryPath & "\Data\Help\" & Page & ".htm")
        ShowHideCutCopyPaster(False)
        Me.InfoBox.Navigate(Page)
        If AutoRefresh = True Then Me.InfoBox.Refresh()
    End Sub
#End Region

#Region "Tree View Contect Menu"

    Private Sub tsRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsRename.Click
        If Me.GgeTreeView1.SelectedNode IsNot Nothing Then
            '==================
            'Rename the project
            '==================
            If CType(GgeTreeView1.SelectedNode.Tag, ClassContainer).ClassType = ClassContainer.enumClassType.Application Then
                Dim o_Widget As Widget = CType(GgeTreeView1.SelectedNode.Tag, ClassContainer).ClassObject
                Dim r As String = InputBox("Rename", "Rename", o_Widget.ProjectName)
                If r <> "" Then
                    o_Widget.ProjectName = r
                    Me.GgeTreeView1.SelectedNode.Text = r
                End If
            End If
        End If
    End Sub
    Private Sub PropertyGrid1_PropertyValueChanged(ByVal s As Object, ByVal e As System.Windows.Forms.PropertyValueChangedEventArgs) Handles PropertyGrid1.PropertyValueChanged
        GgeTreeView1.RefreshNode()
    End Sub
    Private Sub tsAddCodeSnippet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsAddCodeSnippet.Click
        Me.AddCodeSnippet()
    End Sub
    Private Sub tsAddContent_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsAddContent.Click
        Me.AddContent()
    End Sub
    Private Sub tsAddUserPref_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsAddUserPref.Click
        Me.AddUserPref()
    End Sub
    Private Sub tsAddRequirements_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsAddRequirements.Click
        Me.AddRequirements()
    End Sub
    Private Sub tsAddEnum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsAddEnum.Click
        Me.AddEnum()
    End Sub

#End Region

#Region "Methods"
    ''' <summary>
    ''' Build function List from text
    ''' </summary>
    ''' <remarks></remarks>
    Private Function BuildFunctionList(ByVal Text As String) As String()
        'Text = Text.Replace(ControlChars.CrLf, ControlChars.NewLine)
        'Text = Text.Replace(ControlChars.Lf, ControlChars.NewLine)
        'Text = Text.Replace(ControlChars.Cr, ControlChars.NewLine)
        Dim SplitChar() As Char = {ControlChars.NewLine, ControlChars.Lf, ControlChars.Tab, "{", "}", ",", """", ";", ":", "(", ")", "/", "\", "<", ">", "=", " "}
        Dim TempData() As String = Text.Split(SplitChar, StringSplitOptions.RemoveEmptyEntries)

        Dim NextIsName As Boolean = False
        Dim bstr As String = ""

        For i As Integer = 0 To TempData.Length - 1
            TempData(i) = TempData(i).Trim
        Next


        For Each tobj As String In TempData
            tobj = tobj.Trim 'Clean spaces
            If tobj.Contains("function") Then
                NextIsName = True
            Else
                If Not String.IsNullOrEmpty(tobj) Then
                    If NextIsName = True Then
                        Dim TData() As String = tobj.Split("(")
                        If String.IsNullOrEmpty(bstr) Then
                            bstr = TData(0)
                        Else
                            bstr = bstr & "," & TData(0)
                        End If
                        NextIsName = False
                    End If
                End If
            End If
        Next
        Return bstr.Split(",")
    End Function
    ''' <summary>
    ''' Delete Item
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub DeleteItem()
        'Delete the node
        If GgeTreeView1.SelectedNode IsNot Nothing Then
            If GgeTreeView1.SelectedNode.Tag IsNot Nothing Then
                Dim TNodeCLass As ClassContainer = GgeTreeView1.SelectedNode.Tag
                If TNodeCLass.CanDelete = True Then
                    Select Case TNodeCLass.ClassType
                        Case ClassContainer.enumClassType.CodeSnippet
                            Me.o_Widget.Code_Snippets.Remove(TNodeCLass.ClassObject)
                        Case ClassContainer.enumClassType.Content
                            Me.o_Widget.Content.Remove(TNodeCLass.ClassObject)
                        Case ClassContainer.enumClassType.Enum
                            Dim Parent As ClassContainer = GgeTreeView1.SelectedNode.Parent.Tag
                            Dim oUserPref As UserPref = Parent.ClassObject
                            oUserPref.Enums.Remove(TNodeCLass.ClassObject)
                            oUserPref = Nothing
                            Parent = Nothing
                        Case ClassContainer.enumClassType.Require
                            Me.o_Widget.RequireLibs.Remove(TNodeCLass.ClassObject)
                        Case ClassContainer.enumClassType.UserPref
                            Me.o_Widget.ModulePrefs.UserPrefs.Remove(TNodeCLass.ClassObject)
                    End Select
                    GgeTreeView1.SelectedNode.Tag = Nothing
                    GgeTreeView1.Nodes.Remove(GgeTreeView1.SelectedNode)
                End If
            End If
        End If
    End Sub
    ''' <summary>
    ''' Add Requirements
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub AddRequirements()
        Dim o_Object As New Require
        AddItem.AddPropertyGrid.SelectedObject = o_Object
        If AddItem.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.o_Widget.RequireLibs.Add(o_Object)
            GgeTreeView1.AddNodeItem(New ClassContainer(o_Object, ClassContainer.enumClassType.Require, True))
        Else
            o_Object = Nothing
        End If
    End Sub
    ''' <summary>
    ''' add user pref
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub AddUserPref()
        Dim o_Object As New UserPref
        AddItem.AddPropertyGrid.SelectedObject = o_Object
        If AddItem.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.o_Widget.ModulePrefs.UserPrefs.Add(o_Object)
            GgeTreeView1.AddNodeItem(New ClassContainer(o_Object, ClassContainer.enumClassType.UserPref, True))
        Else
            o_Object = Nothing
        End If
    End Sub
    ''' <summary>
    ''' Add enum item
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddEnum()
        If GgeTreeView1.SelectedNode IsNot Nothing Then
            Dim o_UserPref As UserPref = CType(GgeTreeView1.SelectedNode.Tag, ClassContainer).ClassObject
            Dim o_Object As New EnumValue
            AddItem.AddPropertyGrid.SelectedObject = o_Object
            If AddItem.ShowDialog = Windows.Forms.DialogResult.OK Then
                o_UserPref.Enums.Add(o_Object)

                GgeTreeView1.AddNodeItem(New ClassContainer(o_Object, ClassContainer.enumClassType.Enum, True), GgeTreeView1.SelectedNode)
            End If
            o_Object = Nothing
            o_UserPref = Nothing
        End If
    End Sub
    ''' <summary>
    ''' Add content item
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddContent()
        Dim o_Object As New Content
        AddItem.AddPropertyGrid.SelectedObject = o_Object
        If AddItem.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.o_Widget.Content.Add(o_Object)
            GgeTreeView1.AddNodeItem(New ClassContainer(o_Object, ClassContainer.enumClassType.Content, True))
        Else
            o_Object = Nothing
        End If
    End Sub
    'Add a new Code Snippet
    Private Sub AddCodeSnippet()
        Dim o_Object As New CodeSnippet
        AddItem.AddPropertyGrid.SelectedObject = o_Object
        If AddItem.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.o_Widget.Code_Snippets.Add(o_Object)
            GgeTreeView1.AddNodeItem(New ClassContainer(o_Object, ClassContainer.enumClassType.CodeSnippet, True))
        Else
            o_Object = Nothing
        End If
    End Sub
    ''' <summary>
    ''' Show hide Contect menus
    ''' </summary>
    ''' <param name="ItemType"></param>
    ''' <remarks></remarks>
    Private Sub ShowHideContextMenu(ByVal ItemType As ClassContainer.enumClassType)
        '=============
        'Disable Menus
        '=============
        tsRename.Visible = False
        tsRemove.Visible = False
        tsAddEnum.Visible = False
        tsEdit.Visible = False



        'TSBAddCodeSnippet.Enabled = False
        'TSBAddContent.Enabled = False
        TSBAddEnum.Enabled = False
        ' TSBUserPref.Enabled = False
        'TSBAddRequire.Enabled = False

        '==========
        'The reable
        '==========
        Select Case ItemType
            Case ClassContainer.enumClassType.Application 'Application
                tsRename.Visible = True

            Case ClassContainer.enumClassType.CodeSnippet
            Case ClassContainer.enumClassType.Content
                tsEdit.Visible = True
            Case ClassContainer.enumClassType.Enum

            Case ClassContainer.enumClassType.Module
            Case ClassContainer.enumClassType.ModulePrefs
            Case ClassContainer.enumClassType.None
            Case ClassContainer.enumClassType.Require
            Case ClassContainer.enumClassType.RequireLibs
            Case ClassContainer.enumClassType.UserPref
                tsAddEnum.Visible = True
                TSBAddEnum.Enabled = True
            Case ClassContainer.enumClassType.UserPrefs
        End Select
    End Sub
    ''' <summary>
    ''' Open project
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub OpenProject()
        If Me.o_Widget Is Nothing Then
            Me.o_Widget = New Widget
        End If
        If Me.CheckISDirty = True Then
            Dim openFileDialog1 As New OpenFileDialog()
            If String.IsNullOrEmpty(My.Settings.LAST_OPEN_PATH) Then
                openFileDialog1.InitialDirectory = My.Application.Info.DirectoryPath & "\Data\Examples"
            Else
                openFileDialog1.InitialDirectory = My.Settings.LAST_OPEN_PATH
            End If

            openFileDialog1.Filter = "Widget Project  (*.WXml)|*.WXml"
            openFileDialog1.FilterIndex = 1
            openFileDialog1.RestoreDirectory = True
            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Try
                    Me.FileName = openFileDialog1.FileName
                    My.Settings.LAST_OPEN_PATH = IO.Path.GetFullPath(Me.FileName)
                    LoadItems(Me.FileName, Me.o_Widget)
                    ShowHideMenu(False, False, False, False, False)
                    GgeTreeView1.WidgetClass = Me.o_Widget
                    GgeTreeView1.PopulateTree()
                    Me.o_Widget.UnDirty()
                    'Goto Start Screen
                    Me.ShowPreviewScreen(Application.StartupPath & "\Data\Help\Welcome.htm")
                Catch Ex As Exception
                    MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
                Finally

                End Try
            End If
            openFileDialog1 = Nothing
        End If
    End Sub
    ''' <summary>
    ''' Show/Hide The Menu Buttons
    ''' </summary>
    ''' <param name="CodeSnip"></param>
    ''' <param name="Content"></param>
    ''' <param name="Enum"></param>
    ''' <param name="Req"></param>
    ''' <param name="UserP"></param>
    ''' <remarks></remarks>
    Public Sub ShowHideMenu(ByVal CodeSnip As Boolean, ByVal Content As Boolean, ByVal [Enum] As Boolean, ByVal Req As Boolean, ByVal UserP As Boolean)
        Me.tsAddCodeSnippet.Enabled = CodeSnip
        TSBAddCodeSnippet.Enabled = CodeSnip
        Me.tsAddContent.Enabled = Content
        TSBAddContent.Enabled = Content
        Me.tsAddEnum.Enabled = [Enum]
        TSBAddEnum.Enabled = [Enum]
        Me.tsAddRequirements.Enabled = Req
        TSBAddRequire.Enabled = Req
        Me.tsAddUserPref.Enabled = UserP
        TSBUserPref.Enabled = UserP
    End Sub
    ''' <summary>
    ''' Method to checik if the form is dirty then
    ''' Handle saving of project
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckISDirty() As Boolean
        'If dirty ask to save
        If Me.o_Widget.IsDirty = True Then
            Dim r As DialogResult = MsgBox("Save Changes", MsgBoxStyle.YesNoCancel, "Save Changes")
            If r = Windows.Forms.DialogResult.Yes Then
                Me.SaveProject()
                Return True
            ElseIf r = Windows.Forms.DialogResult.No Then
                Return True
            Else
                Return False
            End If
        Else
            Return True
        End If
    End Function
    ''' <summary>
    ''' Download widget from website
    ''' </summary>
    ''' <param name="Url">Url To Website</param>
    ''' <remarks></remarks>
    Private Sub ImportFromUrl(ByVal Url As String)
        Try
            Dim TempFilePath As String = My.Application.Info.DirectoryPath & "\Data\Temp\Temp.xml"
            If Not String.IsNullOrEmpty(Url) Then
                'delete old file
                If My.Computer.FileSystem.FileExists(TempFilePath) Then
                    My.Computer.FileSystem.DeleteFile(TempFilePath)
                End If
                'download te file
                My.Computer.Network.DownloadFile(Url, TempFilePath)
                'see if the file is there and import
                If My.Computer.FileSystem.FileExists(TempFilePath) Then
                    o_Widget = New Widget
                    Me.FileName = ""
                    o_Widget.ImportWidget(TempFilePath)
                    Me.GgeTreeView1.WidgetClass = o_Widget
                    Me.GgeTreeView1.PopulateTree()
                End If
                Me.o_Widget.IsDirty = True
                'Goto Start Screen
                Me.ShowPreviewScreen(Application.StartupPath & "\Data\Help\Welcome.htm")
            End If
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Download widget from website
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ImportFromClipBoard()
        'Try
        Dim TempFilePath As String = My.Application.Info.DirectoryPath & "\Data\Temp\Temp.xml"
        Dim CLipText As String = Clipboard.GetText
        If Not String.IsNullOrEmpty(CLipText) Then
            'delete old file
            If My.Computer.FileSystem.FileExists(TempFilePath) Then
                My.Computer.FileSystem.DeleteFile(TempFilePath)
            End If
            'download te file
            My.Computer.FileSystem.WriteAllText(TempFilePath, CLipText, False, System.Text.Encoding.Default)
            'see if the file is there and import
            If My.Computer.FileSystem.FileExists(TempFilePath) Then
                o_Widget = New Widget
                Me.FileName = ""
                o_Widget.ImportWidget(TempFilePath)
                Me.GgeTreeView1.WidgetClass = o_Widget
                Me.GgeTreeView1.PopulateTree()
            End If
            Me.o_Widget.IsDirty = True
        End If
        ' Catch ex As Exception
        'ErrorHandler.WriteLog(ex.Message)
        ' End Try
    End Sub
    ''' <summary>
    ''' Import the widget from file
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ImportWidgetFromFile()
        Try
            If Me.CheckISDirty() = True Then
                Dim OpenFileDialog As New OpenFileDialog
                OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
                OpenFileDialog.Filter = "Xml File (*.xml)|*.xml"
                If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
                    Dim FileName As String = OpenFileDialog.FileName
                    ' TODO: Add code here to open the file.
                    o_Widget = New Widget
                    o_Widget.ImportWidget(FileName)
                    Me.GgeTreeView1.WidgetClass = o_Widget
                    Me.GgeTreeView1.PopulateTree()
                End If
            End If
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Method to Save the project
    ''' </summary>
    ''' <param name="SaveAs"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SaveProject(Optional ByVal SaveAs As Boolean = False) As Boolean
        Dim SaveObject As New SaveFileDialog
        ' Dim FileName As String = String.Empty
        Try
            With SaveObject
                If String.IsNullOrEmpty(FileName) = True Or SaveAs = True Then
                    .Filter = "Widget Project (*.WXml)|*.WXml"
                    If String.IsNullOrEmpty(My.Settings.LAST_OPEN_PATH) Then
                        .InitialDirectory = My.Application.Info.DirectoryPath & "\Data\Examples"
                    Else
                        .InitialDirectory = My.Settings.LAST_OPEN_PATH
                    End If
                    If .ShowDialog() = DialogResult.OK Then
                        FileName = .FileName
                        My.Settings.LAST_OPEN_PATH = IO.Path.GetFullPath(FileName)
                        If String.IsNullOrEmpty(FileName) = False Then
                            ShowHideMenu(False, False, False, False, False)
                            Me.o_Widget.Save(FileName)
                            Me.o_Widget.UnDirty()
                        End If
                    End If
                Else
                    Me.o_Widget.Save(FileName)
                    Me.o_Widget.UnDirty()
                End If
            End With
        Catch es As Exception
            MessageBox.Show(es.Message)
        Finally

        End Try
    End Function
    ''' <summary>
    ''' lOAD THE WIDGET
    ''' </summary>
    ''' <param name="filename"></param>
    ''' <param name="oWidget"></param>
    ''' <remarks></remarks>
    Private Sub LoadItems(ByVal filename As String, ByRef oWidget As Widget)
        Dim string_reader As IO.StringReader
        Dim Tstr As String = My.Computer.FileSystem.ReadAllText(filename)
        Dim xml_serializer As New XmlSerializer(GetType(Widget))
        ' Make a StringReader holding the serialization.
        string_reader = New IO.StringReader(Tstr)
        ' Create the new Person object from the serialization.
        oWidget = xml_serializer.Deserialize(string_reader)
    End Sub
    ''' <summary>
    ''' Method to convert selected text to Code Snippet
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConvertToSnippet()
        'Convert selected text to code snippet
        If Me.CodeTextBox1.SelectionLength > 0 Then
            'Get the selected text
            Dim Snip As String = Me.CodeTextBox1.SelectedText
            If Not String.IsNullOrEmpty(Snip) Then
                Dim o_CodeSnippet As New CodeSnippet
                o_CodeSnippet.Code = Snip
                AddItem.AddPropertyGrid.SelectedObject = o_CodeSnippet
                If AddItem.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Me.o_Widget.Code_Snippets.Add(o_CodeSnippet)
                    GgeTreeView1.AddNodeItem(New ClassContainer(o_CodeSnippet, ClassContainer.enumClassType.CodeSnippet, True))
                    Me.CodeTextBox1.SelectedText = "<%" & o_CodeSnippet.Name & "%>"
                Else
                    o_CodeSnippet = Nothing
                End If
                GgeTreeView1.RefreshNodes()
            End If
        End If
    End Sub
    ''' <summary>
    ''' Build Output
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub BuildOutPut()
        Try
            'Create output screen
            Dim TOutput As Output
            TOutput = New Output
            'Build and Set the text to the output screen
            TOutput.SetOutput(o_Widget.BuildXml())
            'Show Dialog
            TOutput.ShowDialog()
            TOutput = Nothing
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
        End Try
    End Sub
    Private Sub CloseProject()

    End Sub
    ''' <summary>
    ''' New Project
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub NewProject()
        If o_Widget IsNot Nothing Then
            If Me.CheckISDirty = True Then 'Check if dirty

                Dim TFrm As New frmNew
                If TFrm.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    Me.o_Widget = Nothing 'Clear Widget
                    Me.FileName = ""
                    Dim Name As String = TFrm.ProjectName   'Get project name
                    If Not String.IsNullOrEmpty(Name) Then
                        '====================
                        'Build the new Widget
                        '====================
                        If String.IsNullOrEmpty(TFrm.TemplateName) Then
                            Me.o_Widget = New Widget
                        Else
                            Me.o_Widget = New Widget
                            Me.LoadItems(TFrm.TemplateName, Me.o_Widget)
                        End If

                        Me.o_Widget.ProjectName = Name
                        GgeTreeView1.WidgetClass = Me.o_Widget
                        '=======================
                        'Show Hide menue options
                        '=======================
                        ShowHideMenu(False, False, False, False, False)
                        '=================
                        'Populate the tree
                        '=================
                        GgeTreeView1.PopulateTree()
                        '==================
                        'Set dirty to false
                        '==================
                        Me.o_Widget.IsDirty = True
                        'Goto Start Screen
                        Me.ShowPreviewScreen(Application.StartupPath & "\Data\Help\Welcome.htm")
                    Else
                        MsgBox("Please Enter a project Name")
                    End If
                End If
            End If
        End If
    End Sub
    ''' <summary>
    ''' Build Preview Screen
    ''' </summary>
    ''' <remarks></remarks>
    Private Function BuildPreview() As Boolean
        Try
            Dim NavStr As String = String.Empty
            Dim Tfrm As New TestViews
            Dim TView As String = ""
            If Tfrm.ShowDialog = Windows.Forms.DialogResult.OK Then
                TView = Tfrm.SelectedView
            Else
                TView = ""
            End If
            NavStr = BuildTestUrl(TView)
            Me.ShowPreviewScreen(NavStr)
            Return True
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
            Return False
        End Try
    End Function
    ''' <summary>
    ''' Build the test URL
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function BuildTestUrl(Optional ByVal View As String = "") As String
        Dim NavStr As String = String.Empty

        If String.IsNullOrEmpty(My.Settings.FTP_EXTERNAL_HOST) Then
            MsgBox("Please Enter a value for FTP_EXTERNAL_HOST in settings", MsgBoxStyle.Exclamation)
            Return False
        End If
        If String.IsNullOrEmpty(Me.o_Widget.ProjectName) Then
            MsgBox("Please Enter a Project Name", MsgBoxStyle.Exclamation)
            Return False
        End If
        Dim EXHost As String = My.Settings.FTP_EXTERNAL_HOST.Replace("http://", "")

        Dim URL As String = "http://" & EXHost & "/" & Me.o_Widget.GetCleanedProjectName & ".xml"
        'NavStr = "http://gmodules.com/ig/creator?synd=open&nocache=1&url=" & URL
        'NavStr = "http://www.gmodules.com/ig/ifr?view=&synd=ig&nocache=1&url=" & URL
        NavStr = "http://ig.sandbox.gmodules.com/gadgets/ifr?view=" & View & "&nocache=1&url=" & URL

        'NavStr = "http://www.gmodules.com/ig/ifr?view=" & View & "&nocache=1&url=" & URL

        Return NavStr
    End Function
    ''' <summary>
    ''' Upload Preview
    ''' </summary>
    ''' <remarks></remarks>
    Public Function UploadPreview() As Boolean
        Try
            'CHECK THE SETTIN
            If String.IsNullOrEmpty(My.Settings.FTP_HOST) Then
                MsgBox("Please Enter a value for FTP_HOST in settings", MsgBoxStyle.Exclamation)
                Return False
            End If
            If String.IsNullOrEmpty(My.Settings.FTP_USERNAME) Then
                MsgBox("Please Enter a value for FTP_USERNAME in settings", MsgBoxStyle.Exclamation)
                Return False
            End If
            If String.IsNullOrEmpty(Me.o_Widget.ProjectName) Then
                MsgBox("Please Enter a Project Name", MsgBoxStyle.Exclamation)
                Return False
            End If

            Dim strbuf As String = o_Widget.BuildXml("")
            My.Computer.FileSystem.WriteAllText(My.Application.Info.DirectoryPath & "\" & o_Widget.GetCleanedProjectName & ".xml", strbuf, False, System.Text.Encoding.UTF8)
            Dim FTP As New Utilities.FTP.FTPclient(My.Settings.FTP_HOST, My.Settings.FTP_USERNAME, My.Settings.FTP_PASSWORD)

            If FTP.Upload(My.Application.Info.DirectoryPath & "\" & o_Widget.GetCleanedProjectName & ".xml", o_Widget.GetCleanedProjectName & ".xml") = False Then
                ErrorHandler.WriteLog("Error Uploading File")
            End If

            Return True
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
        End Try
    End Function

    ''' <summary>
    ''' Upload Preview
    ''' </summary>
    ''' <remarks></remarks>
    Public Function BuildTestToFile() As Boolean
        Try
            Dim NavStr As String = ""
            'CHECK THE SETTIN
            'If String.IsNullOrEmpty(My.Settings.FTP_HOST) Then
            '    MsgBox("Please Enter a value for FTP_HOST in settings", MsgBoxStyle.Exclamation)
            '    Return False
            'End If
            'If String.IsNullOrEmpty(My.Settings.FTP_USERNAME) Then
            '    MsgBox("Please Enter a value for FTP_USERNAME in settings", MsgBoxStyle.Exclamation)
            '    Return False
            'End If
            'If String.IsNullOrEmpty(Me.o_Widget.ProjectName) Then
            '    MsgBox("Please Enter a Project Name", MsgBoxStyle.Exclamation)
            '    Return False
            'End If
            Dim ShinDigPath As String = ""
            ShinDigPath = "C:\wamp\www\shindig"
            If My.Computer.FileSystem.FileExists(ShinDigPath & "\" & o_Widget.GetCleanedProjectName & ".xml") Then
                My.Computer.FileSystem.DeleteFile(ShinDigPath & "\" & o_Widget.GetCleanedProjectName & ".xml")
            End If


            Dim Tfrm As New TestViews
            Dim TView As String = ""
            If Tfrm.ShowDialog = Windows.Forms.DialogResult.OK Then
                TView = Tfrm.SelectedView
            Else
                TView = ""
            End If
            Dim strbuf As String = o_Widget.BuildXml(TView)


            My.Computer.FileSystem.WriteAllText(ShinDigPath & "\" & o_Widget.GetCleanedProjectName & ".xml", strbuf, False, System.Text.Encoding.UTF8)

            'http://shindig/gadgets
            ' Me.ShowPreviewScreen()

            NavStr = "http://shindig/gadgets/ifr?url=http://localhost/shindig/" & o_Widget.GetCleanedProjectName & ".xml?synd=open&nocache=1"
            Me.ShowPreviewScreen(NavStr)


            'Dim FTP As New Utilities.FTP.FTPclient(My.Settings.FTP_HOST, My.Settings.FTP_USERNAME, My.Settings.FTP_PASSWORD)

            'If FTP.Upload(My.Application.Info.DirectoryPath & "\" & o_Widget.GetCleanedProjectName & ".xml", o_Widget.GetCleanedProjectName & ".xml") = False Then
            '    ErrorHandler.WriteLog("Error Uploading File")
            'End If

            Return True
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
        End Try
    End Function

    ''' <summary>
    ''' Upload Preview
    ''' </summary>
    ''' <remarks></remarks>
    Public Function BuildUploadUrl() As String
        Try
            'CHECK THE SETTIN
            If String.IsNullOrEmpty(My.Settings.FTP_HOST) Then
                MsgBox("Please Enter a value for FTP_HOST in settings", MsgBoxStyle.Exclamation)
                Return False
            End If
            If String.IsNullOrEmpty(My.Settings.FTP_USERNAME) Then
                MsgBox("Please Enter a value for FTP_USERNAME in settings", MsgBoxStyle.Exclamation)
                Return False
            End If
            If String.IsNullOrEmpty(Me.o_Widget.ProjectName) Then
                MsgBox("Please Enter a Project Name", MsgBoxStyle.Exclamation)
                Return False
            End If
            Return My.Settings.FTP_EXTERNAL_HOST & "\" & o_Widget.GetCleanedProjectName & ".xml"
        Catch ex As Exception
            ErrorHandler.WriteLog(ex.Message)
        End Try
        Return ""
    End Function
    ''' <summary>
    ''' Save as template
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SaveAsTemplate()
        Dim ProjectName As String = InputBox("Enter Project Name", "Save Template")
        If Not String.IsNullOrEmpty(ProjectName) Then
            Dim TPath As String = My.Application.Info.DirectoryPath & "\Data\Project Templates\" & ProjectName & ".TXml"
            Me.o_Widget.Save(TPath)
        End If
    End Sub
#End Region

#Region "Edit context Menu"
    Private Sub InsertJavaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsertJavaToolStripMenuItem.Click
        'Dim TFrm As New CodeTreeDialog
        'TFrm.ShowDialog()
        'TFrm.Dispose()
    End Sub
    Private Sub ConvertToSnippetToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConvertToSnippetToolStripMenuItem.Click
        ConvertToSnippet() 'Convert code to smippet
    End Sub
    Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
        Me.CodeTextBox1.Copy() 'Copy Text
    End Sub
    Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteToolStripMenuItem.Click
        Me.CodeTextBox1.Paste() 'Paste Text
    End Sub
    Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CutToolStripMenuItem.Click
        Me.CodeTextBox1.Cut() 'Cut Text
    End Sub
    Private Sub SelectAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectAllToolStripMenuItem.Click
        Me.CodeTextBox1.SelectAll() 'SelectAll Text
    End Sub
    Private Sub RefreshToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsRefresh.Click
        GgeTreeView1.RefreshNodes()
    End Sub
#End Region

#Region "Tool strip"
    Private Sub ImportWidgetFromUrlToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportWidgetFromUrlToolStripMenuItem.Click
        '  Try
        If Me.CheckISDirty = True Then
            Dim r As String = InputBox("Widget Url", "Widget Url")
            If Not String.IsNullOrEmpty(r) Then
                ImportFromUrl(r)
            End If
        End If
        ' Catch ex As Exception
        'ErrorHandler.WriteLog(ex.Message)
        '  End Try
    End Sub
    Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripButton.Click
        OpenProject()
    End Sub
    Private Sub SaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripButton.Click
        SaveProject()
    End Sub

    Private Sub NewToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripButton.Click
        NewProject() 'Create a new project
    End Sub
    Private Sub HelpToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpToolStripButton.Click
        Dim Thelp As New frmHelp
        Thelp.Show()
        'If TSHelpList.Text <> "" Then
        '    Me.ShowInfoScreen(TSHelpList.Text)
        'End If
    End Sub
    Private Sub TSBBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBBack.Click
        InfoBox.GoBack()
    End Sub
    Private Sub TSBForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBForward.Click
        InfoBox.GoForward()
    End Sub
    Private Sub TSBHome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBHome.Click
        ShowInfoScreen("HOME")
    End Sub
    Private Sub CopyToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToolStripButton.Click
        Me.CodeTextBox1.Copy()
    End Sub
    Private Sub CutToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CutToolStripButton.Click
        Me.CodeTextBox1.Cut()
    End Sub
    Private Sub PasteToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteToolStripButton.Click
        Me.CodeTextBox1.Paste()
    End Sub
#End Region

#Region "Menu strip"
    Private Sub CloseProjectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseProjectToolStripMenuItem.Click
        NewProject()
    End Sub
    Private Sub ImportFromClipBoardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportFromClipBoardToolStripMenuItem.Click
        ImportFromClipBoard()
    End Sub
    Private Sub SaveAsTemplateToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsTemplateToolStripMenuItem.Click
        SaveAsTemplate()
    End Sub
    Private Sub BuildWidgetToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BuildWidgetToolStripMenuItem.Click
        BuildOutPut()
    End Sub
    Private Sub TSBPreviewScreen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBPreviewScreen.Click
        BuildPreview()
    End Sub
    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
        NewProject()
    End Sub
    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        OpenProject()
    End Sub
    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        SaveProject()
    End Sub
    Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
        SaveProject(True)
    End Sub
    Private Sub CopyTestUrlToClipboardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyTestUrlToClipboardToolStripMenuItem.Click
        Clipboard.Clear()
        Clipboard.SetText(BuildTestUrl)
    End Sub
    Private Sub CopyUrlToClipboardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyUrlToClipboardToolStripMenuItem.Click
        Clipboard.Clear()
        Clipboard.SetText(BuildUploadUrl)
    End Sub
    Private Sub BuildAndUploadToTestSiteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BuildAndUploadToTestSiteToolStripMenuItem.Click
        ShowPreviewScreen(My.Application.Info.DirectoryPath & "\Data\Output\PleaseWaitScreen.htm", False)
        Application.DoEvents()

        If UploadPreview() = True Then
            Application.DoEvents()
            BuildPreview()
        Else
            Me.ShowPreviewScreen(Application.StartupPath & "\Data\Help\Welcome.htm")
            Application.DoEvents()
        End If
    End Sub
    Private Sub ImportXmlWidgetToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportXmlWidgetToolStripMenuItem.Click
        'Import widget from xml file
        ImportWidgetFromFile()
    End Sub
    Private Sub OptionsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OptionsToolStripMenuItem.Click
        Dim TFrm As New frmOptions
        TFrm.ShowDialog()
    End Sub
    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim Tfrm As New frmAboutBox
        Tfrm.ShowDialog()
    End Sub
    Private Sub CutToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CutToolStripMenuItem1.Click
        Me.CodeTextBox1.Cut()
    End Sub
    Private Sub CopyToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToolStripMenuItem1.Click
        Me.CodeTextBox1.Copy()
    End Sub
    Private Sub PasteToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteToolStripMenuItem1.Click
        Me.CodeTextBox1.Paste()
    End Sub
    Private Sub SelectAllToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectAllToolStripMenuItem1.Click
        Me.CodeTextBox1.SelectAll()
    End Sub
    Private Sub CodeManagerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CodeManagerToolStripMenuItem.Click
        Dim TFrm As New frmCodeManager
        TFrm.ShowDialog()
        CodeTree1.LoadData(My.Application.Info.DirectoryPath & "\Data\Java\Java.xml")
    End Sub
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub
    Private Sub DeleteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteToolStripMenuItem.Click
        Me.DeleteItem()
    End Sub
#End Region

#Region "Tag Build and Insert Menu"
    'Handle the Tag and insert events 
    Private Sub cmEditor_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmEditor.Opening
        Dim o_Tags As New StringReplaceTags
        For Each TContent As UserPref In Me.o_Widget.ModulePrefs.UserPrefs
            o_Tags.AddTag("__UP_" & TContent.Name & "__")
        Next
        InsertReplaceTagToolStripMenuItem.DropDownItems.Clear()
        For Each TTag As StringReplaceTag In o_Tags
            Dim TTStrItem As ToolStripItem = InsertReplaceTagToolStripMenuItem.DropDownItems.Add(TTag.Name)
            AddHandler TTStrItem.Click, AddressOf InsertTag_Click
        Next

        'Function context menu
        Dim Temp() As String = BuildFunctionList(Me.CodeTextBox1.Text)
        InsertFunctionNameToolStripMenuItem.DropDownItems.Clear()
        For Each o_Name As String In Temp
            Dim TTStrItem As ToolStripItem = InsertFunctionNameToolStripMenuItem.DropDownItems.Add(o_Name)
            AddHandler TTStrItem.Click, AddressOf InsertFunctionName_Click
        Next
    End Sub
    Private Sub InsertTag_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.CodeTextBox1.SelectedText = sender.text

    End Sub
#End Region

#Region "Tree Tool Strip  Menu"
    Private Sub ToolStripRefreshTree_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripRefreshTree.Click
        GgeTreeView1.RefreshNodes()
    End Sub
    Private Sub ToolStripRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripRefresh.Click
        Me.InfoBox.Refresh()
    End Sub
    Private Sub TSBAddCodeSnippet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBAddCodeSnippet.Click
        AddCodeSnippet()
    End Sub
    Private Sub TSBAddContent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBAddContent.Click
        AddContent()
    End Sub
    Private Sub TSBAddEnum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBAddEnum.Click
        Me.AddEnum()
    End Sub
    Private Sub TSBUserPref_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBUserPref.Click
        Me.AddUserPref()
    End Sub
    Private Sub TSBAddRequire_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBAddRequire.Click
        Me.AddRequirements()
    End Sub
    Private Sub TSBDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBDelete.Click
        Me.DeleteItem()
    End Sub
#End Region



#Region "Insert Tag Commands"
    'Public Sub SetupMenuItem3()
    '    Dim Item As String = ""
    '    Dim ItemInsert As String = ""
    '    Dim Description As String = ""
    '    Dim SubItem As ToolStripMenuItem = Nothing

    '    '================================
    '    '_IG_RegisterOnloadHandler(init);
    '    '================================
    '    ' AddEditMenuItem("_IG_RegisterOnloadHandler(init);", "_IG_RegisterOnloadHandler(init);", "_IG_RegisterOnloadHandler(init);")

    '    '========
    '    '_gel(id)
    '    '========
    '    SubItem = AddEditMenuItem("_gel(id)", "_gel(id)", "_gel(id)", "")
    '    Item = "_gel(id).innerHTML = ""text"";"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "")
    '    Item = "_gel(id).appendChild(p);"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "")

    '    '====
    '    'Tabs
    '    '====
    '    Item = "Tabs"
    '    Description = "Tabs"
    '    SubItem = AddEditMenuItem(Item, Description, "", "tabs")

    '    '=========
    '    'initilise
    '    '=========
    '    Item = " var tabs = new _IG_Tabs(__MODULE_ID__, ""Two""); "
    '    Description = "Initialize tabs, designate the tab named 'Two' as  the tab selected by default."
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "tabs")

    '    '========
    '    'Add Tabs
    '    '========
    '    Item = "var one_Id = tabs.addTab(""One"");"
    '    Description = "Capture the tab's ID when you create it, and use the ID to add content to the tab's corresponding <div>:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "tabs")

    '    Item = "tabs.addTab(""Two"", ""two_id"");"
    '    Description = "Create the tab and add a corresponding <div> to the HTML portion of the gadget; place static content in the <div>:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "tabs")

    '    Item = "tabs.addTab(""Three"", ""three_id"", callback);"
    '    Description = "Create the tab and add a corresponding <div> to the HTML portion of the gadget; place static content in the <div>. Use a callback function to add dynamic content to the static content:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "tabs")

    '    Item = "tabs.addTab(""Four"", {contentContainer: _gel(""four_id""),callback: callback,tooltip: ""I'm special""});"
    '    Description = "Use the addTab(tabName, opt_params) function to add a tab by name. For example:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "tabs")
    '    '===========
    '    'Select Tabs
    '    '===========
    '    Item = "tabs.setSelectedTab(1);"
    '    Description = "Select Tab"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "tabs")

    '    Item = "tabs.swapTabs(0, 1);"
    '    Description = "Swap Tabs"
    '    AddEdiSubItemMenuItem(SubItem, Item, Item, Item, "tabs")

    '    Item = "tabs.alignTabs(""left"", 10);"
    '    Description = "Align tabs to the left and offset it by 10 pixels"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "tabs")

    '    Item = "tabs.displayTabs(true);"
    '    Description = "show/hide tabs"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "tabs")
    '    '==============
    '    'Mini Messagage
    '    '==============
    '    Item = "MiniMessages"
    '    Description = "Mini Messages"
    '    SubItem = AddEditMenuItem(Item, Description, "", "minimessage")
    '    '=========
    '    'initilise
    '    '=========
    '    Item = "var msg = new _IG_MiniMessage(__MODULE_ID__);"
    '    Description = "Instantiate a new MiniMessage object using the gadgets.MiniMessage() constructor:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "minimessage")

    '    Item = "var msg = new gadgets.MiniMessage(__MODULE_ID__, document.getElementById(""messageBox""));"
    '    Description = "Instantiate a new MiniMessage object using the gadgets.MiniMessage() constructor: and set the location"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "minimessage")
    '    '==================
    '    'Create the message
    '    '==================
    '    Item = "msg.createDismissibleMessage(""Please close me when you're done reading me."");"
    '    Description = "Create a new MiniMessage with some text:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "minimessage")

    '    '==================
    '    'Create the message
    '    '==================
    '    Item = "msg.createTimerMessage(""I'm going to disappear in 5 seconds."", 5);"
    '    Description = "Create a timed new MiniMessage with some text:"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "minimessage")


    '    '==============
    '    'Mini Messagage
    '    '==============
    '    Item = "Flash"
    '    Description = "Flash"
    '    SubItem = AddEditMenuItem(Item, Description, "", "flash")


    '    Item = "_IG_embedFlash(url, ""flashcontainer"", {swf_version: 6, id: ""flashid"",width: 300,height: 250})"
    '    Description = "Embed Flash Control"
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "flash")

    '    '==============
    '    'Remote content
    '    '==============
    '    '==============
    '    'Mini Messagage
    '    '==============
    '    Item = "Remote Content"
    '    Description = "Remote Content"
    '    SubItem = AddEditMenuItem(Item, Description, "", "")

    '    Item = "_IG_FetchContent(url, func)"
    '    Description = "Returns and operates on the content at url as text. This is the function you should use for working with HTML content."
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "")

    '    Item = "_IG_FetchXmlContent(\url, func)"
    '    Description = "Returns and operates on the XML content at url as a DOM object."
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "")

    '    Item = "_IG_FetchFeedAsJSON(url, func, num_entries, get_summaries)"
    '    Description = "Returns and operates on the feed content at url in JSON format."
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, Item, "")

    '    Item = "Example:function my_callback_function(responseText)"
    '    ItemInsert = " function my_callback_function(responseText) {%nl%if (responseText == null) return;%nl%alert(responseText.substr(0,400));%nl%}%nl%// Here the callback is invoked by name %nl%_IG_FetchContent('http://www.google.com/', my_callback_function);"
    '    Description = "Returns and operates on the feed content at url in JSON format."
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, ItemInsert.Replace("%nl%", ControlChars.NewLine), "")

    '    Item = "Example:_IG_FetchXmlContent(\url, func)"
    '    ItemInsert = " IG_FetchXmlContent(url, function (response) {%nl%" _
    '        & "if (response == null || typeof(response) != ""object"" || %nl%" _
    '        & "           response.firstChild == null) {%nl%" _
    '        & "   _gel(""content_div"").innerHTML = ""<i>Invalid data.</i>"";%nl%" _
    '        & "   return;%nl%" _
    '        & "}"
    '    Description = "Returns and operates on the XML content at url as a DOM object."
    '    AddEdiSubItemMenuItem(SubItem, Item, Description, ItemInsert.Replace("%nl%", ControlChars.NewLine), "")


    '    '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

    ' End Sub
    ''' <summary>
    ''' Load the code insert list
    ''' </summary>
    ''' <param name="filename"></param>
    ''' <remarks></remarks>
    Private Sub LoadCodeStoreItems(ByVal filename As String)
        Dim string_reader As IO.StringReader
        Dim Tstr As String = My.Computer.FileSystem.ReadAllText(filename)
        Dim xml_serializer As New XmlSerializer(GetType(CodeStoreCollection))
        ' Make a StringReader holding the serialization.
        string_reader = New IO.StringReader(Tstr)
        ' Create the new Person object from the serialization.
        o_CodeStoreCollection = xml_serializer.Deserialize(string_reader)

    End Sub
    ''' <summary>
    ''' Set up the menu items
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub SetupCodeMenuItem()
        Dim Item As String = ""
        Dim ItemInsert As String = ""
        Dim Description As String = ""
        Dim SubItem As ToolStripMenuItem = Nothing
        Dim o_Item As ToolStripMenuItem = Nothing
        Dim SubItem2 As ToolStripMenuItem = Nothing

        For Each Tobj As CodeStore In Me.o_CodeStoreCollection
            'set the root menue item
            o_Item = InsertJavaToolStripMenuItem

            Dim Name_Spaces() As String = Tobj.Name_Space.Split(".")
            For i As Integer = 0 To Name_Spaces.Length - 1
                If o_Item.DropDownItems.ContainsKey(Name_Spaces(i)) Then
                    o_Item = o_Item.DropDownItems(Name_Spaces(i))
                Else
                    o_Item = o_Item.DropDownItems.Add(Name_Spaces(i), Nothing)
                    o_Item.ToolTipText = Tobj.Description
                    o_Item.Name = Name_Spaces(i)
                End If

            Next


            '============
            'Add the Item
            '============
            If o_Item IsNot Nothing Then
                SubItem = o_Item.DropDownItems.Add(Tobj.Name, Nothing, AddressOf EditMenuItem_Click)
                SubItem.Tag = Tobj
                SubItem.ToolTipText = Tobj.Description

                If Not String.IsNullOrEmpty(Tobj.Code) Then
                    SubItem2 = SubItem.DropDownItems.Add("Old Api Code", Nothing, AddressOf EditMenuItem_Click)
                    SubItem2.Tag = Tobj
                    SubItem2.ToolTipText = Tobj.Description
                End If

                If Not String.IsNullOrEmpty(Tobj.Code2) Then
                    SubItem2 = SubItem.DropDownItems.Add("New Api Code", Nothing, AddressOf EditMenuItem_Click)
                    SubItem2.Tag = Tobj
                    SubItem2.ToolTipText = Tobj.Description
                End If

                If Not String.IsNullOrEmpty(Tobj.Example) Then
                    SubItem2 = SubItem.DropDownItems.Add("Example Code", Nothing, AddressOf EditMenuItem_Click)
                    SubItem2.Tag = Tobj
                    SubItem2.ToolTipText = Tobj.Description
                End If
            End If
        Next



    End Sub

    Private Sub EditMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim o_Code As CodeStore = Nothing
        If TypeOf sender.Tag Is CodeStore Then
            o_Code = sender.Tag
            If Not String.IsNullOrEmpty(o_Code.RequireLib) Then
                If Me.o_Widget.RequireLibs.HasReqLib(o_Code.RequireLib) = False Then
                    Me.o_Widget.RequireLibs.Add(o_Code.RequireLib)
                End If
            End If
            Select Case sender.text.ToString
                Case "Old Api Code"
                    Me.CodeTextBox1.SelectedText = o_Code.Code
                Case "New Api Code"
                    Me.CodeTextBox1.SelectedText = o_Code.Code2
                Case "Example Code"
                    'Me.CodeTextBox1.SelectedText = o_Code.
                Case Else
                    Me.CodeTextBox1.SelectedText = o_Code.Code
            End Select
        End If
    End Sub

#End Region

#Region "Code edit box"

    Private Sub CodeTextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles CodeTextBox1.KeyPress
        If e.KeyChar = ControlChars.Tab Then
            ' If CodeTextBox1.Lines Then
            CodeTextBox1.SelectedText = ControlChars.Tab
            e.Handled = True
        End If
    End Sub
    Private Sub UndoToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UndoToolStripMenuItem1.Click
        CodeTextBox1.Undo()
    End Sub
    Private Sub RedoToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RedoToolStripMenuItem1.Click
        CodeTextBox1.Redo()
    End Sub
    Private Sub CodeTextBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CodeTextBox1.MouseMove
        StripLine.Text = "Line:" & CodeTextBox1.GetLineFromCharIndex(CodeTextBox1.SelectionStart)
    End Sub
#End Region


    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        o_CodeStoreCollection = New CodeStoreCollection
    End Sub

#Region "Function Build and Insert Menu"
    Private Sub InsertFunctionNameToolStripMenuItem_DropDownOpening(ByVal sender As Object, ByVal e As System.EventArgs) Handles InsertFunctionNameToolStripMenuItem.DropDownOpening
        Dim Temp() As String = BuildFunctionList(Me.CodeTextBox1.Text)
        InsertFunctionNameToolStripMenuItem.DropDownItems.Clear()
        For Each o_Name As String In Temp
            Dim TTStrItem As ToolStripItem = InsertFunctionNameToolStripMenuItem.DropDownItems.Add(o_Name)
            AddHandler TTStrItem.Click, AddressOf InsertFunctionName_Click
        Next
    End Sub

    Private Sub InsertFunctionName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.CodeTextBox1.SelectedText = sender.text
    End Sub
#End Region


End Class
